package com.yuntsg.nnsfcp.service.back.Role;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuntsg.nnsfcp.common.exceptions.BaseResponseCode;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.nnsfcp.common.utils.VerifyUtil;
import com.yuntsg.nnsfcp.entity.PermissionRespNode;
import com.yuntsg.nnsfcp.entity.RolePermissionOperationReqVO;
import com.yuntsg.nnsfcp.entity.UserRole;
import com.yuntsg.nnsfcp.front.entity.Employee;
import com.yuntsg.nnsfcp.front.entity.TRole;
import com.yuntsg.nnsfcp.front.entity.TUserRole;
import com.yuntsg.nnsfcp.front.mapper.EmployeeMapper;
import com.yuntsg.nnsfcp.front.mapper.TRoleMapper;
import com.yuntsg.nnsfcp.front.mapper.TUserRoleMapper;
import com.yuntsg.nnsfcp.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author 葛成瑞
 * @crete 2021/1/22
 */
@Service
@Slf4j
public class EmRoleService {

    //人员角色表操作

    @Resource
    UserUtil userUtil;

    @Resource
    TRoleMapper tRoleMapper;

    @Resource
    RolePermissionService rolePermissionService;

    @Resource
    EmployeeMapper employeeMapper;

    @Resource
    TUserRoleMapper tUserRoleMapper;

    @Resource
    CommonService commonService;

    public List<Employee> handleRols(String username, Integer role, Integer status, Integer type) {
        if (type == 1) {
            List<TRole> tRoles = tRoleMapper.selectList(new LambdaQueryWrapper<>());
            List<TUserRole> tUserRoles = tUserRoleMapper.selectList(new QueryWrapper<>());
            QueryWrapper queryWrapper = new QueryWrapper();
            if (!StringUtils.isEmpty(username)) {
                queryWrapper.like("user_name", username);
            }
            List<Integer> uids = new ArrayList<>();
            if (!StringUtils.isEmpty(role) && role != 0) {
                if (tUserRoles.size() > 0) {
                    uids = tUserRoles.stream().filter(o -> o.getRoleId().equals(role)).map(o -> o.getUserId()).collect(Collectors.toList());
                }
            }
            if (status != null) {
                queryWrapper.eq("status", status);
            }
            if (uids.size() > 0) {
                queryWrapper.in("id", uids);
            }
            List<Employee> userLS = employeeMapper.selectList(queryWrapper);
            //2021年9月16日09:50:17  如果不是单位管理员 只能看自己的内容

            String roleName = commonService.getRoleNameByUid(userUtil.getBackUserInfo().getId());

            if (!roleName.contains("单位管理员")) {
                userLS = Stream.of(employeeMapper.selectById(userUtil.getBackUserInfo().getId())).collect(Collectors.toList());
            }

            userLS.forEach(user -> {
                user.setFlag(0);
            });
            userLS.forEach(ee -> {
                //设置回显的密码 进行设置显示原密码
                List<Integer> roleIds = tUserRoles.stream().filter(o -> o.getUserId().equals(ee.getId())).map(o -> o.getRoleId()).collect(Collectors.toList());
                setCheck(tRoles, ee, roleIds);
            });
            return userLS;
        } else {
            List<Employee> userLS = employeeMapper.selectList(new QueryWrapper<Employee>().eq("id", userUtil.getBackUserInfo().getId()));
            return userLS;
        }

    }

    //2021年1月24日09:40:27

    /**
     * 给每个人设置角色 如果有的话就给个check 没有就不给了
     *
     * @param ls
     * @param employee
     * @param erids
     */
    public void setCheck(List<TRole> ls, Employee employee, List<Integer> erids) {
        List<UserRole> resUserRole = new ArrayList<>();
        StringBuffer roBuffer = new StringBuffer();
        for (TRole l : ls) {
            UserRole userRole = new UserRole();
            if (erids.contains(l.getId())) {
                userRole.setRoleId(l.getId());
                userRole.setRoleName(l.getName());
                userRole.setCheck(true);
                roBuffer.append(l.getName() + ",");
            } else {
                userRole.setRoleId(l.getId());
                userRole.setRoleName(l.getName());
                userRole.setCheck(false);
            }
            resUserRole.add(userRole);
            employee.setUserRoles(resUserRole);
            if (roBuffer.toString().length() > 0) {
                String roleName = roBuffer.toString().substring(0, roBuffer.toString().length() - 1);
                employee.setRoleName(roleName);
            }
        }

    }

    @Transactional
    public boolean insertEm(Employee employee) {
        boolean flag = false;
        if (StringUtils.isEmpty(employee.getRoleids())) {
            CheckUtil.check(false, "请勾选角色");
        }
        //处理角色
        int s = employeeMapper.insert(employee);
        flag = insertRole(employee.getId(), employee.getRoleids());
        if (!flag) {
            CheckUtil.check(false, "插入用户异常");
        }
        return flag;
    }

//    @Transactional
//    public void testException() {
//        Employee employee = new Employee();
//        employee.setUserName("2252525");
//        employee.setOpenPassword("2252525");
//        employee.setPassword("2252525");
//        employee.setRand("2252525");
//        employee.setStatus(0);
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setFlag(0);
//        employeeMapper.insert(employee);
//        tUserRoleMapper.insert(new TUserRole().setRoleId(1).setUserId(2));
//        CheckUtil.check(false, "yichangas");
//    }


    @Transactional
    public boolean updateEmRole(Integer uid, String roleIds) {
        boolean flag = false;
        List<TUserRole> tUserRoles = tUserRoleMapper.selectList(new QueryWrapper<TUserRole>().eq("user_id", uid));
        if (tUserRoles.size() > 0) {
            //先删除再插入
            List<Integer> delIds = tUserRoles.stream().map(o -> o.getId()).collect(Collectors.toList());
            int i = tUserRoleMapper.deleteBatchIds(delIds);
            flag = insertRole(uid, roleIds);
            log.info("删除了uid是" + uid + "角色条数" + i);
        } else {
            //直接进行插入
            flag = insertRole(uid, roleIds);
        }
        if (!flag) {
            CheckUtil.check(false, "更新异常");
        }
        return flag;
    }


    @Transactional
    public boolean insertRole(Integer uid, String roleIds) {
        boolean flag = false;
        try {
            List<Integer> roles = Arrays.asList(roleIds.split(",")).stream().map(o -> Integer.valueOf(o)).collect(Collectors.toList());
            for (Integer role : roles) {
                TUserRole tUserRole = new TUserRole();
                tUserRole.setUserId(uid);
                tUserRole.setRoleId(role);
                tUserRole.setCreated(LocalDateTime.now());
                tUserRoleMapper.insert(tUserRole);
            }
            flag = true;
        } catch (Exception e) {
        }
        if (!flag) {
            CheckUtil.check(false, "插入用户异常");
        }
        return flag;
    }


    @Transactional
    public TRole addRole(TRole vo) {
        int insert = tRoleMapper.insert(vo);
        if (insert != 1) {
            CheckUtil.check(false, BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        if (null != vo.getPermissions() && !vo.getPermissions().isEmpty()) {
            RolePermissionOperationReqVO reqVO = new RolePermissionOperationReqVO();
            reqVO.setRoleId(vo.getId());
            reqVO.setPermissionIds(vo.getPermissions());
            rolePermissionService.addRolePermission(reqVO);
        }
        return vo;
    }

    @Transactional
    public void updateRole(TRole vo) {
        TRole Role = tRoleMapper.selectById(vo.getId());
        if (null == Role) {
            log.error("传入 的 id:{}不合法", vo.getId());
            VerifyUtil.verify(true, BaseResponseCode.DATA_ERROR.getMsg());
        }
        int i = tRoleMapper.updateById(vo);
        if (i != 1) {
            VerifyUtil.verify(true, BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        rolePermissionService.removeByRoleId(Role.getId());
        if (!CollectionUtils.isEmpty(vo.getPermissions())) {
            RolePermissionOperationReqVO reqVO = new RolePermissionOperationReqVO();
            reqVO.setRoleId(Role.getId());
            reqVO.setPermissionIds(vo.getPermissions());
            rolePermissionService.addRolePermission(reqVO);
            //刷新权限
//            httpSessionService.refreshRolePermission(Role.getId());
        }
    }

    public TRole detailInfo(Integer id) {
        TRole Role = tRoleMapper.selectById(id);
        if (Role == null) {
            log.error("传入 的 id:{}不合法", id);
            VerifyUtil.verify(true, BaseResponseCode.DATA_ERROR.getMsg());
        }
        List<PermissionRespNode> permissionRespNodes = commonService.selectAllByTree();
        Set<Integer> checkList = new HashSet<>(rolePermissionService.getPermissionIdsByRoleId(Role.getId()));
        setheckced(permissionRespNodes, checkList);
        Role.setPermissionRespNodes(permissionRespNodes);
        return Role;
    }


    private void setheckced(List<PermissionRespNode> list, Set<Integer> checkList) {
        for (PermissionRespNode node : list) {
            if (checkList.contains(node.getId()) && (node.getChildren() == null || node.getChildren().isEmpty())) {
                node.setChecked(true);
            }
            setheckced((List<PermissionRespNode>) node.getChildren(), checkList);
        }
    }


    public IPage pageInfo(TRole vo) {
        Page page = new Page(vo.getPage(), vo.getLimit());
        QueryWrapper queryWrapper = new QueryWrapper();
        if (!StringUtils.isEmpty(vo.getName())) {
            queryWrapper.like("name", vo.getName());
        }
        if (!StringUtils.isEmpty(vo.getStatus())) {
            queryWrapper.eq("status", vo.getStatus());
        }
        queryWrapper.orderByDesc("gen_time");
        return tRoleMapper.selectPage(page, queryWrapper);
    }

    public List<TRole> selectAllRoles() {
        return tRoleMapper.selectList(new QueryWrapper<TRole>().ne("id", 3));
    }
}
